package com.sykj.bsc.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sykj.bsc.cl.bean.ErrorInfo;
import com.sykj.bsc.cl.bean.TokenBean;
import com.sykj.bsc.cl.bean.WechatUser;
import com.sykj.bsc.constant.WechatCons;

import redis.clients.jedis.Jedis;

public class WechatUtil {

	public static String getOauth2Url(String redirect_uri,String grant_type) {
		// 获取公众号唯一凭证
		System.out.println("跳转地址：" + redirect_uri);
		String appid =PropUtil.getString("wechat.appID");
		String request_url =PropUtil.getString("wechat.server"); // 系统请求的地址
		redirect_uri = request_url + "/" + redirect_uri;
		String scope = "snsapi_base";
		if(grant_type.equals("1")){
			scope = "snsapi_userinfo";
		}
		String oauth2Url=WechatCons.OAUTH2_AUTHORIZE_URL+"?appid="+appid+"&redirect_uri="+
                redirect_uri+"&response_type=code&scope="+scope+"&state=1#wechat_redirect";
		return oauth2Url;
	}
	
	public static TokenBean getOauth2Token(String code) {
		// 获取公众号唯一凭证
		String appid = PropUtil.getString("wechat.appID");
		// 获取公众号户唯一凭证密钥
		String secret =PropUtil.getString("wechat.appsecret");
		
		return getOauth2Token(appid, secret, code);
	}
	
	 /**
     * 
     * 简要说明：通过code换取网页网页授权accessToken
     * @param 说明
     * @return 说明
     */
	public static TokenBean getOauth2Token(String appid,String secret,String code){
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("appid", appid);
		map.put("secret", secret);
		map.put("code", code);
		map.put("grant_type", "authorization_code");
		String returnMsg=HttpRequestProxy.doGet(WechatCons.OAUTH2__TOKEN_URL,map);
		System.out.println("获取微信网页授权接口返回信息："+returnMsg);
		TokenBean token=JsonUtils.jsonToPojo(returnMsg,TokenBean.class);
		if(Tools.isNotNull(token.getErrcode())){
			System.out.println("获取微信接口出错");
			return null;
		}
		return token;
	}
	
	public static TokenBean getToken(String appid,String secret){
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("appid", appid);
		map.put("secret", secret);
		map.put("grant_type", "client_credential");
		String returnMsg=HttpRequestProxy.doGet(WechatCons.ACCESS_TOKEN_URL,map);
		System.out.println("获取微信网页授权接口返回信息："+returnMsg);
		TokenBean token=JsonUtils.jsonToPojo(returnMsg,TokenBean.class);
		if(Tools.isNotNull(token.getErrcode())){
			System.out.println("获取微信接口出错");
			return null;
		}
		return token;
	}
	
	public static  WechatUser getOAuthUserInfo(String code) {
		   TokenBean token=getOauth2Token(code);
		   return getOAuthUserInfo(token.getAccess_token(), token.getOpenid());
		}
	
	public static WechatUser getOAuthUserInfo(String access_token,String openid){
		Map<String,Object> paramDto=new HashMap<String,Object>();
		paramDto.put("access_token", access_token);
		paramDto.put("openid", openid);
		paramDto.put("lang", "zh_CN");
		String returnMsg=HttpRequestProxy.doGet(WechatCons.OAUTH2__URER_URL,paramDto);
		System.out.println("网页授权获取微信用户基本信息接口返回信息："+returnMsg);
		WechatUser user=JsonUtils.jsonToPojo(returnMsg, WechatUser.class);
		if(Tools.isNotNull(user.getErrcode())){
			System.out.println("获取用户信息出错:"+user.getErrcode()+","+user.getErrmsg());
			return null;
		}
		return user;
	}
	
	public static String getAccessToken() {
		// 获取公众号唯一凭证
		String appid = PropUtil.getString("wechat.appID");
		// 获取公众号户唯一凭证密钥
		String secret =PropUtil.getString("wechat.appsecret");
		String accessTokenKey = WechatCons.ACCESS_TOKEN_KEY;
		String accessToken = "";
		if (JedisUtil.isLive()) {
			Jedis jedis = JedisUtil.getJedisClient();
			if (jedis.exists(accessTokenKey)) { // 如果redis中存在accessToken的键，则还没失效直接取出来
				accessToken = jedis.get(accessTokenKey);
			} else {
				TokenBean token = getToken(appid, secret);
				if (token!=null) {
					accessToken = token.getAccess_token();
					jedis.set(accessTokenKey, accessToken);
					jedis.expire(accessTokenKey, token.getExpires_in());
				}
			}
			JedisUtil.close(jedis);
		} else {
			TokenBean token = getToken(appid, secret);
			if (token!=null&&Tools.isNotNull(token.getAccess_token())) {
				accessToken = token.getAccess_token();

			}
		}
		return accessToken;
	}
	
	/**
	 * 给微信号发信息
	 * @param mobile
	 * @param accessToken
	 */
	public static boolean sendTextMessage(List<String> mobile,String msg){
		String accessToken=getAccessToken();
		Map<String,Object> tuser=new HashMap<String,Object>();
		Map<String,Object> content=new HashMap<String,Object>();
		Map<String,Object> map=new HashMap<String,Object>();
		tuser.put("touser",mobile);
		content.put("content", msg);
		map.put("text",content);
		map.put("msgtype", "text");
		String json=JsonUtils.objectToJson(map);
		System.out.println("json:"+json);
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("access_token", accessToken);
		String returnMsg=HttpRequestProxy.doJsonPost(WechatCons.SEND_MESSAGE_URL, param,json);
		System.out.println("发送文本信息接口返回信息："+returnMsg);
		ErrorInfo info=JsonUtils.jsonToPojo(returnMsg, ErrorInfo.class);
		if(!"0".equals(info.getErrcode())){
			System.out.println("文本消息群发失败！errcode=" +info.getErrcode() + ",errmsg = " +info.getErrmsg());
			return false;
		}
		return true;
	}
}
